package com.lungle.warmdiary.app.view.wallet.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.PayAccountPost;
import com.lungle.warmdiary.app.model.response.AlipayAccount;
import com.lungle.warmdiary.app.ui.InputItemView;
import com.lungle.warmdiary.app.utils.CountDownTimerUtil;
import com.lungle.warmdiary.app.utils.StringUtils;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BindAccountFragment extends BaseFragment {
    private static final String BIND_ACCOUTN_SCREEN = "bind account screen";

    @Bind(R.id.et_username)
    InputItemView mEtName;
    @Bind(R.id.et_account)
    InputItemView mEtAccount;
    @Bind(R.id.btn_login)
    Button mBtnSubmit;
    @Bind(R.id.et_capture)
    EditText mEtCapture;
    @Bind(R.id.btn_captcha)
    Button mBtnCaptcha;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        initData();
        initView(view);

        return view;
    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this, view);
        timer = CountDownTimerUtil.create(mBtnCaptcha);
    }

    @Override
    public void initData() {


    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(BIND_ACCOUTN_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(BIND_ACCOUTN_SCREEN);
        MobclickAgent.onPause(getActivity());

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_bind_account;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.btn_captcha, R.id.btn_login})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_login:
                String capture = mEtCapture.getText().toString();
                String account = mEtAccount.getInputText();
                String name = mEtName.getInputText();
                if (prepareSubmit(account, name)) {
                    submit(capture, name, account);
                }
                break;

            case R.id.btn_captcha:

                String phone = AppContext.getInstance().getLoginUser().getCellphone();
                if (prepareCapture(phone)) {
                    getCapture(phone);
                }

                break;
        }

    }


    private boolean prepareCapture(String phone) {
        if (TextUtils.isEmpty(phone)) {
            AppContext.showToast("请输入手机号");
            return false;
        }

        if (!StringUtils.isPhone(phone)) {
            AppContext.showToast("非法手机号");
            return false;
        }
        return true;

    }

    private boolean prepareSubmit(String account, String name) {
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(name)) {
            AppContext.showToast("信息不完整");
            return false;
        }
        return true;
    }


    private void submit(String capture, final String account, final String name) {
        showWaitDialog();
        PayAccountPost.AccountPost post = new PayAccountPost.AccountPost(capture, account, name);
        PayAccountPost alipayUpdatePost = new PayAccountPost(post);

        ApiFactory.getUserApi().updateAlipayState(alipayUpdatePost).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<AlipayAccount>>(getActivity()) {
                    @Override
                    public void onNext(Result<AlipayAccount> alipayAccountResult) {
                        AppContext.showToast("绑定成功");
                        AlipayAccount data = alipayAccountResult.getData();
                        AlipayAccount alipayAccount = new AlipayAccount();
                        alipayAccount.setId(data.getId());
                        alipayAccount.setAccount(account);
                        alipayAccount.setAccountName(name);
                        UIHelper.showAccountCenter(getActivity(), alipayAccount);

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiException exception = (ApiException) e;
                            ApiErrorHelper.showErrorDetail(exception.getExtendErrorMsg());
                        }
                        hideWaitDialog();
                    }

                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        getActivity().finish();
                    }
                });
    }

    public void getCapture(String phone) {
        showWaitDialog("正在获取...");
        ApiFactory.getBaseApi().getCapture(phone, 3).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>() {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiErrorHelper.showErrorDetail(((ApiException) e).getExtendErrorMsg());
                        }
                        hideWaitDialog();
                    }

                    @Override
                    public void onCompleted() {
                        AppContext.showToast("验证码已发送");
                        hideWaitDialog();
                        timer.start();
                    }
                });
    }


    @Override
    public void onDetach() {
        super.onDetach();
        timer.cancel();
    }

    private CountDownTimer timer ;

}
